package frontend.pages.settings.resetpassword;

import backend.model.other.User;
import backend.service.base.DBModelService;
import backend.service.other.UserService;
import frontend.components.form.ValidatableForm;
import frontend.components.other.UserSelectionPanel;
import frontend.core.TimeTrackingWebApplication;
import frontend.model.settings.SettingsUIModel;
import frontend.pages.admin.base.AbstractManagingForm;
import org.apache.log4j.Logger;
import org.apache.wicket.Localizer;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.validation.ValidationError;
import shared.util.MD5CryptographyUtil;

public class ResetPasswordForm extends ValidatableForm<SettingsUIModel> {
    private static Logger logger = Logger.getLogger(ResetPasswordForm.class);

    private static final String RESOURCE_KEY_FIELD_LABEL_USER = "pages.resetPassword.form.user";

    public ResetPasswordForm(String id, SettingsUIModel model) {
        super(id,  model);
    }

    protected void constructFormContent() {
        Panel userToUpdatePassword = new UserSelectionPanel("otherUserToUpdatePassword", uiModel, null, RESOURCE_KEY_FIELD_LABEL_USER);
        AjaxButton resetPasswordButton = createResetPasswordButton();
        add(userToUpdatePassword, resetPasswordButton);
    }

    private AjaxButton createResetPasswordButton() {
        AjaxButton resetPasswordButton = new AjaxButton("resetPassword", this) {
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                boolean successful = resetUserPassword();
                if (successful) {
                        setResponsePage(ResetPasswordPage.class, new PageParameters().add(AbstractManagingForm.PAGE_PARAMETER_KEY_OPERATION_SUCCESSFUL,
                            Localizer.get().getString(AbstractManagingForm.RESOURCE_KEY_INFO_ENTITY_SAVED_SUCCESSFULLY, null)));
                }
                target.add(feedbackPanel);
            }

            private boolean resetUserPassword() {
                validationErrors.clear();
                doFormValidation();

                if (validationErrors.size() > 0) {
                    for (ValidationError validationError : validationErrors) {
                        error(validationError.getMessage());
                    }
                    return false;
                } else {
                    User user = uiModel.getUser();
                    user.setPassword(MD5CryptographyUtil.encrypt("temp"));
                    DBModelService service = TimeTrackingWebApplication.getService(UserService.class);
                    service.saveOrUpdateDBModel(user);
                    return true;
                }
            }

            @Override
            protected void onError(AjaxRequestTarget target, Form<?> form) {
                logger.error("Error occurred while submitting form.");
            }
        };
        return resetPasswordButton;
    }

    @Override
    protected void doFormValidation() {
        validateNotEmpty(uiModel.getUser(), RESOURCE_KEY_FIELD_LABEL_USER);
    }
}